// 运行时配置
import { notification } from 'antd';
import type { RequestConfig } from 'umi';
import { history } from 'umi';
import { API_URL, LOGIN_PATH, NORMAL_CODE, NO_LOGIN_CODE } from '@/constants';
import { getAuthUserApi } from './services/auth/auth';
import {getListsApi as getAppListsApi, getMenuApi as getAppMenuApi} from './services/app/app';

// 全局初始化数据配置
export async function getInitialState() {
  // 如果是登录页面，不执行
  if (history.location.pathname !== LOGIN_PATH) {
    //获取用户信息
    try {
      const res = await getAuthUserApi({}, { notice: true });
      if (res.code === NORMAL_CODE) {
        return {
          authData: res.data,
        };
      }
      return {};
    } catch (error) {
      history.push(LOGIN_PATH);
    }
  }
}

// 在初始加载和路由切换时
export function onRouteChange({ location, clientRoutes, routes, action }) {
  // console.log(location, clientRoutes, routes, action);
}


// 运行时配置
export const request: RequestConfig = {
  // 统一的请求设定
  timeout: 6000,
  headers: { 'X-Requested-With': 'XMLHttpRequest' },
  errorConfig: {
    // 错误抛出
    errorThrower: () => { },
    // 错误接收及处理
    errorHandler: (error: any, opts: any) => {
      if (opts?.skipErrorHandler) throw error;
      if (error.response) {
        // Axios 的错误 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围
        notification['error']({
          message: '请求失败',
          description: error.response.status,
        });
      } else if (error.request) {
        // 请求已经成功发起，但没有收到响应
        notification['error']({
          message: '请求失败',
          description: '服务器未响应',
        });
      } else {
        // 发送请求时出了点问题
        notification['error']({
          message: '请求失败',
          description: '发生异常',
        });
        throw error;
      }
    },

  },

  // 请求拦截器
  requestInterceptors: [
    (config) => {
      // 拦截请求配置，进行个性化处理。
      const token = localStorage.getItem('token');
      config.headers.Authorization = 'Bearer ' + (token === null ? '' : token);
      config.url = API_URL.concat(config.url);
      return { ...config };
    }
  ],

  // 响应拦截器
  responseInterceptors: [
    (response) => {
      // 拦截响应数据，进行个性化处理
      const { data, config } = response;
      if (config.notice === true) {
        switch (data.code) {
          case NORMAL_CODE:
            notification['success']({
              message: '请求成功',
              description: data.msg,
            });
            break;
          default:
            notification['error']({
              message: '请求失败',
              description: data.msg,
            });
            break;
        }
      }
      //判断是否全局码
      switch (data.code) {
        case NO_LOGIN_CODE:
          if(history){
            history.push(LOGIN_PATH);
          }
          break;
        default:
          break;
      }
      return response;
    }
  ]
};

// 从接口中获取子应用配置，export 出的 qiankun 变量是一个 promise
export const qiankun = async () => {
  const res = await getAppListsApi({}, { notice: true });
  const loader = (loading: boolean) => {
    // 此处可以获取微应用是否加载成功,可以用来触发全局的 loading
    // console.log('loading', loading);
  };
  let appList = [];
  if (res.code === NORMAL_CODE) {
    const getActiveRule = (hash) => (location) => location.hash.startsWith(hash);
    appList = res.data.list.map((item) => {
      return {
        //name: 微应用的名称,
        //entry: 微应用的入口,
        //container: 微应用的容器节点的选择器或者 Element 实例,
        //activeRule: 激活微应用的规则(可以匹配到微应用的路由),
        //loader: 加载微应用的状态 true | false
        name: item.name,
        entry: item.url,
        container: '#subContainer',
        activeRule: getActiveRule(item.rule),
        loader,
      }
    })
  }
  return {
    // 注册子应用信息
    apps: appList,
    // 完整生命周期钩子请看 https://qiankun.umijs.org/zh/api/#registermicroapps-apps-lifecycles
    lifeCycles: {
      // qiankun 生命周期钩子 - 微应用加载前
      beforeLoad: (app: any) => {
        // console.log('子应用 before load', app.name);
        return Promise.resolve();
      },
      // qiankun 生命周期钩子 - 微应用挂载后
      afterMount: (app: any) => {
        // console.log('子应用 after mount', app.name);
        return Promise.resolve();
      },
    },
    // 支持更多的其他配置，详细看这里 https://qiankun.umijs.org/zh/api/#start-opts
  }
};


//动态路由(未实现)
export function patchRoutes(res) {
  // console.log('patchRoutes')
  // console.log(res)

}
export const patchClientRoutes = async ({routes}) => {
  const res = await getAppMenuApi({}, { notice: true });
  if (res.code === NORMAL_CODE) {
    const funC = (list) => {
      return list.map((item) => {
        const route = {
          name: item?.name,
          icon: item?.icon,
          path: item?.path,
          routes: [],
        };
        if(item.children){
          route.routes = funC(item.children);
        }
        return route;
      })
    }
    routes.map((route) => {
      if(route.path === '/apps'){
        route.routes = [];
        funC(res.data.list).map((item)=>{
          route.routes.push(item)
        })
      }
    });
  }
}
export async function render(oldRender) {
  oldRender();
}
